package micotime.com.amap_plugin.map;

import android.content.Context;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationListener;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import micotime.com.amap_plugin.map.common.LocationUtils;

/**
 * 高德定位功能
 */
public class AMapLocation implements MethodChannel.MethodCallHandler,
        EventChannel.StreamHandler {

    final static String LOCATION_METHOD_CHANNEL = "location_method_channel";

    //开始定位
    final static String METHOD_START_LOCATION = "startLocation";

    //停止定位
    final static String METHOD_STOP_LOCATION = "stopLocation";

    //获取定位信息
    final static String METHOD_GET_LOCATION = "getLocation";

    //定位数据事件
    final static String LOCATION_EVENT_CHANNEL = "location_event_channel";

    //坐标信息
    private static Map<String,Object> mLocation;

    //事件Sink
    private static EventChannel.EventSink mEventSink;

    private AMapLocationClient aMapLocationClient = null;

    public AMapLocation(Context context){
        this.aMapLocationClient = new AMapLocationClient(context);
        aMapLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(com.amap.api.location.AMapLocation aMapLocation) {
                mLocation = LocationUtils.getLocationInfoMap(aMapLocation);
                mEventSink.success(new JSONObject(mLocation).toString());
            }
        });
    }

    public void cancelListen(){
        aMapLocationClient.stopLocation();
    }

    public void register(BinaryMessenger messenger){
        final MethodChannel channel = new MethodChannel(messenger, LOCATION_METHOD_CHANNEL);
        final EventChannel eventChannel = new EventChannel(messenger, LOCATION_EVENT_CHANNEL);
        eventChannel.setStreamHandler(this);
        channel.setMethodCallHandler(this);
    }

    @Override
    public void onListen(Object o, EventChannel.EventSink eventSink) {
        mEventSink = eventSink;
    }

    @Override
    public void onCancel(Object o) {
        cancelListen();
    }

    @Override
    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
        switch (methodCall.method) {
            case METHOD_STOP_LOCATION:
                aMapLocationClient.stopLocation();
                break;
            case METHOD_START_LOCATION:
                aMapLocationClient.startLocation();
                break;
            case METHOD_GET_LOCATION:
                if(mLocation != null){
                    result.success(new JSONObject(mLocation).toString());
                }
                break;
            default:
                result.notImplemented();
                break;
        }
    }
}

